Xceed DataGrid for WPF v7.2 Documentation
Retrieving a DataRow from a Data Item

Welcome to Xceed DataGrid, Editors, and 3D Views for WPF v7.2 > Xceed DataGrid for WPF > Code Snippets > Retrieving a DataRow from a Data Item

The following example demonstrates how to retrieve a DataRow (container) for a data item using the GetContainerFromItem method. It is important to remember that data rows are virtualized; therefore, references to them or their cells should never be kept.

VB.NET
Copy Code
Public Sub New()
  InitializeComponent()
  Dim grid As New DataGridControl()
  Dim view As New DataGridCollectionView( App.Orders.DefaultView )
  grid.ItemsSource = view
  ' Subscribe to the PropertyChanged event to know when the CurrentItem property changes.
  AddHandler grid.PropertyChanged, AddressOf grid_PropertyChanged
  Me.Content = grid
End Sub
Private Sub grid_PropertyChanged( ByVal sender As Object, _
                                 ByVal e As System.ComponentModel.PropertyChangedEventArgs )
  If e.PropertyName = "CurrentItem" Then
    ' Retrieve the data-row container for the current item. Can be Nothing if the data item
    ' is not in the viewport.
    Dim grid As DataGridControl = CType( sender, DataGridControl )
    Dim row As Xceed.Wpf.DataGrid.DataRow = TryCast( grid.GetContainerFromItem( grid.CurrentItem ), Xceed.Wpf.DataGrid.DataRow )
    ' Change the background of the data row to pink. Data rows are recycled once they
    ' exit the viewport; therefore, any modifications made to a data row will
    ' be discarded once it is no longer in the viewport.
    row.Background = Brushes.Pink
  End If
End Sub
C#
Copy Code
public Window1()
{
  InitializeComponent();
  DataGridControl grid = new DataGridControl();   
    
  DataGridCollectionView view = new DataGridCollectionView( App.Orders.DefaultView );
  grid.ItemsSource = view;
  // Subscribe to the PropertyChanged event to know when the CurrentItem property changes.
  grid.PropertyChanged +=
        new System.ComponentModel.PropertyChangedEventHandler( grid_PropertyChanged );    
    
  this.Content = grid;
}
void grid_PropertyChanged( object sender, System.ComponentModel.PropertyChangedEventArgs e )
{
  if( e.PropertyName == "CurrentItem" )
  {
    // Retrieve the data-row container for the current item. Can be null if the data item
    // is not in the viewport.
    DataGridControl grid = sender as DataGridControl;
    Xceed.Wpf.DataGrid.DataRow row = grid.GetContainerFromItem( grid.CurrentItem ) as Xceed.Wpf.DataGrid.DataRow;
    // Change the background of the data row to pink. Data rows are recycled once they
    // exit the viewport; therefore, any modifications made to a data row will
    // be discarded once it is no longer in the viewport.
    row.Background = Brushes.Pink;
  }
}